package vn.co.thn.android.serviceconnect.request;

import java.util.ArrayList;

import android.os.Handler;
import android.os.Message;

import vn.co.thn.android.serviceconnect.TaskObject;
import vn.co.thn.android.serviceconnect.callback.RequestProcessCallBack;

public class ServiceTask {
	private RequestProcessCallBack mRequestProcessCallBack;
	private ArrayList<TaskObject> mListRequest = new ArrayList<TaskObject>();
	private int mCountTask;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (mRequestProcessCallBack != null) {
				mRequestProcessCallBack.HideProcess();
			}
		}
	};

	public void add(RequestService requestService, int processType) {
		mListRequest.add(new TaskObject(requestService, processType));
	}

	public void setRequestProcessCallBack(RequestProcessCallBack processCallBack) {
		this.mRequestProcessCallBack = processCallBack;
	}

	public void start() {
		if (mRequestProcessCallBack != null) {
			mRequestProcessCallBack.ShowProcess();
		}
		new Thread() {
			public void run() {

				mCountTask = mListRequest.size();
				for (TaskObject requestService : mListRequest) {
					requestService.getRequestService().setTaskRequest(new TaskRequest() {

						@Override
						public synchronized void TaskComplete() {
							// TODO Auto-generated method stub
							mCountTask = mCountTask - 1;
						}
					});
					if (requestService.getProcessType() == 1) {
						requestService.getRequestService().Post();
					} else if (requestService.getProcessType() == 2) {
						requestService.getRequestService().PostAndCache();
					}

				}
				while (mCountTask > 0) {
					try {
						sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				mHandler.sendEmptyMessage(0);

			}
		}.start();
	}

	public interface TaskRequest {
		public void TaskComplete();
	}
}
